<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="第六章：块与大中枢派发(3)第44条：通过 Dispatch Group，根据系统资源状况来执行任务dispatch group 是 GCD 的一项特性，能够把任务分组。调用者可以等待这组任务执行完毕，也可以在提供回调函数之后继续往下执行，这组任务完成时，调用者会得到通知。通过这个功能可以把将要并发执行的多个任务合为一组，于是调用者就可以知道这些任务何时才能全部执行完毕。 创建 dispatch">
<meta property="og:type" content="article">
<meta property="og:title" content="《Effective Objective-C 2.0》第六章阅读笔记(3)">
<meta property="og:url" content="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%85%AD%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(3)/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:description" content="第六章：块与大中枢派发(3)第44条：通过 Dispatch Group，根据系统资源状况来执行任务dispatch group 是 GCD 的一项特性，能够把任务分组。调用者可以等待这组任务执行完毕，也可以在提供回调函数之后继续往下执行，这组任务完成时，调用者会得到通知。通过这个功能可以把将要并发执行的多个任务合为一组，于是调用者就可以知道这些任务何时才能全部执行完毕。 创建 dispatch">
<meta property="og:locale">
<meta property="article:published_time" content="2018-05-23T16:00:00.000Z">
<meta property="article:modified_time" content="2018-07-01T08:21:26.857Z">
<meta property="article:author" content="vhuichen">
<meta property="article:tag" content="GCD">
<meta property="article:tag" content="Effective Objective-C 2.0">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%85%AD%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(3)/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-Hans","comments":true,"permalink":"https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%85%AD%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(3)/","path":"2018/05/2018/05/《Effective Objective-C 2.0》第六章阅读笔记(3)/","title":"《Effective Objective-C 2.0》第六章阅读笔记(3)"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>《Effective Objective-C 2.0》第六章阅读笔记(3) | vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">vhuichen</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%AC%AC%E5%85%AD%E7%AB%A0%EF%BC%9A%E5%9D%97%E4%B8%8E%E5%A4%A7%E4%B8%AD%E6%9E%A2%E6%B4%BE%E5%8F%91-3"><span class="nav-number">1.</span> <span class="nav-text">第六章：块与大中枢派发(3)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC44%E6%9D%A1%EF%BC%9A%E9%80%9A%E8%BF%87-Dispatch-Group%EF%BC%8C%E6%A0%B9%E6%8D%AE%E7%B3%BB%E7%BB%9F%E8%B5%84%E6%BA%90%E7%8A%B6%E5%86%B5%E6%9D%A5%E6%89%A7%E8%A1%8C%E4%BB%BB%E5%8A%A1"><span class="nav-number">1.1.</span> <span class="nav-text">第44条：通过 Dispatch Group，根据系统资源状况来执行任务</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA-dispatch-group"><span class="nav-number">1.1.0.1.</span> <span class="nav-text">创建 dispatch group</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#dispatch-apply"><span class="nav-number">1.1.0.2.</span> <span class="nav-text">dispatch_apply</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">1.1.1.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC45%E6%9D%A1%EF%BC%9A%E4%BD%BF%E7%94%A8-dispath-once-%E6%9D%A5%E6%89%A7%E8%A1%8C%E5%8F%AA%E9%9C%80%E8%BF%90%E8%A1%8C%E4%B8%80%E6%AC%A1%E7%9A%84%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E4%BB%A3%E7%A0%81"><span class="nav-number">1.2.</span> <span class="nav-text">第45条：使用 dispath_once 来执行只需运行一次的线程安全代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC46%E6%9D%A1%EF%BC%9A%E4%B8%8D%E8%A6%81%E4%BD%BF%E7%94%A8-dispatch-get-current-queue"><span class="nav-number">1.3.</span> <span class="nav-text">第46条：不要使用 dispatch_get_current_queue</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93-1"><span class="nav-number">1.3.1.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%85%AD%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(3)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="《Effective Objective-C 2.0》第六章阅读笔记(3) | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          《Effective Objective-C 2.0》第六章阅读笔记(3)
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-05-24 00:00:00" itemprop="dateCreated datePublished" datetime="2018-05-24T00:00:00+08:00">2018-05-24</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:21:26" itemprop="dateModified" datetime="2018-07-01T16:21:26+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="第六章：块与大中枢派发-3"><a href="#第六章：块与大中枢派发-3" class="headerlink" title="第六章：块与大中枢派发(3)"></a><center>第六章：块与大中枢派发(3)</center></h1><h2 id="第44条：通过-Dispatch-Group，根据系统资源状况来执行任务"><a href="#第44条：通过-Dispatch-Group，根据系统资源状况来执行任务" class="headerlink" title="第44条：通过 Dispatch Group，根据系统资源状况来执行任务"></a>第44条：通过 Dispatch Group，根据系统资源状况来执行任务</h2><p>dispatch group 是 GCD 的一项特性，能够把任务分组。调用者可以等待这组任务执行完毕，也可以在提供回调函数之后继续往下执行，这组任务完成时，调用者会得到通知。通过这个功能可以把将要并发执行的多个任务合为一组，于是调用者就可以知道这些任务何时才能全部执行完毕。</p>
<h4 id="创建-dispatch-group"><a href="#创建-dispatch-group" class="headerlink" title="创建 dispatch group"></a>创建 dispatch group</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dispatch_group_t group = dispatch_group_create();</span><br></pre></td></tr></table></figure>

<p>想把任务分组，有两种办法。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> dispatch_group_async(dispatch_group_t group, <span class="built_in">dispatch_queue_t</span> queue, dispatch_block_t block);</span><br></pre></td></tr></table></figure>

<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">dispatch_group_enter(dispatch_group_t group);</span><br><span class="line"><span class="comment">// task</span></span><br><span class="line">dispatch_group_leave(dispatch_group_t group);</span><br></pre></td></tr></table></figure>
<p>判断任务完成也有两种方法<br>第一种方法是同步的，等到所有任务完成，才能继续往下执行。  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> dispatch_group_wait(dispatch_group_t group, dispatch_time_t timeout);</span><br></pre></td></tr></table></figure>
<p>第二种方法是异步的，当所有的任务执行完成，就会触发这个通知。  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> dispatch_group_notify(dispatch_group_t group, <span class="built_in">dispatch_queue_t</span> queue, dispatch_block_t block);</span><br></pre></td></tr></table></figure>

<p>如果想令数组中的每个对象都执行某项任务，并且想等待所有任务执行完毕，那么就可以使用这个GCD特性来实现。同时还可以给任务加上优先级。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">dispatch_queue_t</span> lowPriorityQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, <span class="number">0</span>); </span><br><span class="line"><span class="built_in">dispatch_queue_t</span> highPriorityQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, <span class="number">0</span>); </span><br><span class="line">dispatch_group_t dispatchGroup = dispatch_group_create();</span><br><span class="line"></span><br><span class="line"><span class="built_in">NSArray</span> *lowPriorityObject;</span><br><span class="line"><span class="built_in">NSArray</span> *highPriorityObject;</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="type">id</span> object <span class="keyword">in</span> lowPriorityObject) &#123; </span><br><span class="line">	dispatch_group_async(dispatchGroup, lowPriorityQueue, ^&#123; </span><br><span class="line">		[object task];</span><br><span class="line">	&#125;); </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="type">id</span> object <span class="keyword">in</span> highPriorityObject) &#123; </span><br><span class="line">	dispatch_group_async(dispatchGroup, highPriorityQueue, ^&#123; </span><br><span class="line">		[object task]; </span><br><span class="line">	&#125;); </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^&#123; </span><br><span class="line">	</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>除了像上面这样把任务提交到并发队列之外，也可以把任务提交至各个串行队列中，并用 dispatch group 跟踪其执行状况。如果所有任务都排在同一个串行队列里面，那么 dispatch group 就用处不大了。因为此时，任务总要逐个执行，所以只需在提交完全部任务之后再提交一个块即可，这样做与通过 notify 函数等待 dispatch group 执行完毕后再回调块是等效的。</p>
</blockquote>
<h4 id="dispatch-apply"><a href="#dispatch-apply" class="headerlink" title="dispatch_apply"></a>dispatch_apply</h4><p>dispatch_apply 也是并发，并且是阻塞的，所以有时候我们完全可以使用 dispatch_apply 来代替 dispatch group 来执行任务。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">dispatch_queue_t</span> queue = dispatch_queue_create(<span class="string">&quot;com.vhuichen.queue&quot;</span>, <span class="literal">NULL</span>); </span><br><span class="line">dispatch_apply(count, queue, ^(size_t i) &#123; </span><br><span class="line">	<span class="comment">//Perform task </span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>当有一组任务需要执行时，可以将这一组任务加到 dispatch group 中，当所有任务执行完成后会收到一个通知。</p>
<h2 id="第45条：使用-dispath-once-来执行只需运行一次的线程安全代码"><a href="#第45条：使用-dispath-once-来执行只需运行一次的线程安全代码" class="headerlink" title="第45条：使用 dispath_once 来执行只需运行一次的线程安全代码"></a>第45条：使用 dispath_once 来执行只需运行一次的线程安全代码</h2><p>单例模式（singleton）是我们常用的一种开发模式，常见的一种写法如下：  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">+ (<span class="keyword">instancetype</span>)sharedInstance &#123; </span><br><span class="line">	<span class="keyword">static</span> <span class="type">id</span> sharedInstance = <span class="literal">nil</span>; </span><br><span class="line">	<span class="keyword">@synchronized</span> (<span class="keyword">self</span>) &#123; </span><br><span class="line">		<span class="keyword">if</span> (!sharedInstance) &#123; </span><br><span class="line">			sharedInstance = [[<span class="keyword">self</span> alloc] init]; </span><br><span class="line">		&#125; </span><br><span class="line">	&#125; </span><br><span class="line">	<span class="keyword">return</span> sharedInstance; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>也可以通过 GCD 的 dispath_once 来实现，dispath_once 是线程安全的。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">+ (<span class="keyword">instancetype</span>)sharedInstance &#123; </span><br><span class="line">	<span class="keyword">static</span> <span class="type">id</span> sharedInstance = <span class="literal">nil</span>; </span><br><span class="line">	<span class="keyword">static</span> <span class="built_in">dispatch_once_t</span> onceToken; </span><br><span class="line">	<span class="built_in">dispatch_once</span>(&amp;onceToken, ^&#123; </span><br><span class="line">		sharedInstance = [[<span class="keyword">self</span> alloc] init]; </span><br><span class="line">	&#125;);</span><br><span class="line">	<span class="keyword">return</span> sharedInstance; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>使用 dispath_once 方式比 @synchronized 方式要快很多</p>
</blockquote>
<h2 id="第46条：不要使用-dispatch-get-current-queue"><a href="#第46条：不要使用-dispatch-get-current-queue" class="headerlink" title="第46条：不要使用 dispatch_get_current_queue"></a>第46条：不要使用 dispatch_get_current_queue</h2><p>使用 GCD 时，经常需要判断当前代码正在哪个队列上执行，文档提供了这个函数：  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">dispatch_queue_t</span> dispatch_get_current_queue();</span><br></pre></td></tr></table></figure>
<p>iOS6.0 开始已经正式弃用此函数了。这个函数有个典型的错误用法，就是用它来检测当前队列是不是某个特定的队列，试图以此来避免执行同步派发时可能遇到的死锁问题。<br>下面两个存取方法，用串行队列保证实例变量的访问是线程安全的。  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="built_in">NSString</span> *)someString &#123;</span><br><span class="line">	__block <span class="built_in">NSString</span> *localSomeString;</span><br><span class="line">	<span class="built_in">dispatch_sync</span>(_syncQueue, ^&#123;</span><br><span class="line">		localSomeString = _someString;</span><br><span class="line">	&#125;);</span><br><span class="line">	<span class="keyword">return</span> localSomeString;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="type">void</span>)setSomeString:(<span class="built_in">NSString</span> *)someString &#123;  </span><br><span class="line">	<span class="built_in">dispatch_async</span>(_syncQueue, ^&#123;</span><br><span class="line">		_someString = someString;</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这种写法的问题在于，getter 方法可能会死锁（当 getter 方法恰好就是 _syncQueue 时）。<br>可以将上面的代码稍作修改，只需先判断当前队列是否为 _syncQueue 队列，如果是就不派发，直接执行。这样做就可以另其变得“可重入”</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="built_in">NSString</span> *)someString &#123;</span><br><span class="line">	__block <span class="built_in">NSString</span> *localSomeString;</span><br><span class="line">	dispatch_block_t accessorBlock = ^&#123;</span><br><span class="line">		localSomeString = _someString;</span><br><span class="line">	&#125;;</span><br><span class="line">   </span><br><span class="line">	<span class="keyword">if</span> (dispatch_get_current_queue() == _syncQueue) &#123;</span><br><span class="line">		accessorBlock();</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="built_in">dispatch_sync</span>(_syncQueue, accessorBlock);  </span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> localSomeString;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样做好像是可以解决问题，但有些情况下还是会出现死锁问题，例如下面的例子：  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">dispatch_queue_t</span> queueA = dispatch_queue_create(<span class="string">&quot;com.vhuichen.queueA&quot;</span>, <span class="literal">NULL</span>);  </span><br><span class="line"><span class="built_in">dispatch_queue_t</span> queueB = dispatch_queue_create(<span class="string">&quot;com.vhuichen.queueB&quot;</span>, <span class="literal">NULL</span>);  </span><br><span class="line"></span><br><span class="line"><span class="built_in">dispatch_sync</span>(queueA, ^&#123;</span><br><span class="line">	<span class="built_in">dispatch_sync</span>(queueB, ^&#123;</span><br><span class="line">		dispatch_block_t block = ^&#123; <span class="comment">/* ... */</span> &#125;;</span><br><span class="line">		<span class="keyword">if</span> (dispatch_get_current_queue() == queueA) &#123;</span><br><span class="line">			block();</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="built_in">dispatch_sync</span>(queueA, block);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面的代码依然会出现死锁。也就是说想通过 dispatch_get_current_queue 来避免死锁问题是不可能的。  </p>
<p>有的 API 可令开发者指定运行回调时所用的队列，但实际上却会把回调块安排在内部的串行同步队列上，而内部队列的目标队列又是开发者所提供的那个队列，那么就会出现死锁。使用 API 的开发者认为在回调块里调用 dispatch_get_current_queue 返回的“当前队列”，总是调用 API 时指定的那个，但实际返回的却是 API 内部的那个队列。  </p>
<p>要解决这个问题，最好的办法是通过 GCD 所提供的功能来设定“队列特有数据”（ queue_specific data ），此功能可以把任意数据以键值对的形式关联到队列里。假如根据指定的键值对获取不到关联数据，那么系统会沿着层级体系一直向上找，直到找到数据或者到达根队列为止。看看下面的例子：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">dispatch_queue_t</span> queueA = dispatch_queue_create(<span class="string">&quot;com.vhuichen.queueA&quot;</span>, <span class="literal">NULL</span>);</span><br><span class="line"><span class="built_in">dispatch_queue_t</span> queueB = dispatch_queue_create(<span class="string">&quot;com.vhuichen.queueB&quot;</span>, <span class="literal">NULL</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="type">int</span> kQueueSpecific;</span><br><span class="line"><span class="built_in">CFStringRef</span> queueSpecificValue = <span class="built_in">CFSTR</span>(<span class="string">&quot;queueA&quot;</span>);</span><br><span class="line">dispatch_queue_set_specific(queueA, &amp;kQueueSpecific, (<span class="type">void</span> *)queueSpecificValue,  (dispatch_function_t)<span class="built_in">CFRelease</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">dispatch_sync</span>(queueB, ^&#123;</span><br><span class="line">	dispatch_block_t block = ^&#123; <span class="built_in">NSLog</span>(<span class="string">@&quot;no deadlock&quot;</span>); &#125;;</span><br><span class="line">	<span class="built_in">CFStringRef</span> retrievedValue = dispatch_get_specific(&amp;kQueueSpecific);</span><br><span class="line">	<span class="keyword">if</span> (retrievedValue) &#123;</span><br><span class="line">		block();</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="built_in">dispatch_sync</span>(queueA, block);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>使用 “队列特有数据”（ queue_specific data ）则可以避免由不可重入引发的死锁。  </p>
<h3 id="总结-1"><a href="#总结-1" class="headerlink" title="总结"></a>总结</h3><p>dispatch_get_current_queue 函数无法解决由不可重入引发的死锁问题，但“队列特有数据”（ queue_specific data ）可以解决此问题。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/GCD/" rel="tag"># GCD</a>
              <a href="/tags/Effective-Objective-C-2-0/" rel="tag"># Effective Objective-C 2.0</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%85%AD%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(2)/" rel="prev" title="《Effective Objective-C 2.0》第六章阅读笔记(2)">
                  <i class="fa fa-chevron-left"></i> 《Effective Objective-C 2.0》第六章阅读笔记(2)
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%83%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/" rel="next" title="《Effective Objective-C 2.0》第七章阅读笔记(1)">
                  《Effective Objective-C 2.0》第七章阅读笔记(1) <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
